package com.woniuxy.lab.woniu_lab.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.lab.woniu_lab.commons.Result;
import com.woniuxy.lab.woniu_lab.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component// 登录认证拦截器
public class Authentication implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;// 用于josn和字符串互转

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 字符编码设置
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        // token验证
        String token = JwtUtil.getTokenFromReq();

        //请求头中没有带令牌
        if (!StringUtils.hasLength(token)){
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail(401,"当前用户尚未登录")));
            response.sendRedirect("./login.html");
            return false;
        }
        // 请求头中带了令牌
        try {
            JwtUtil.parseToken(token);
            return true;
        } catch (Exception e) {
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail(401,"当前用户尚未登录")));
            response.sendRedirect("./login.html");
            return false;
        }
    }

}
